<template>
  <div class="base-box-wrap page-wrap">
    <Tooltip transfer content="更多筛选项">
      <Checkbox v-model="isMoreFilter"></Checkbox>
    </Tooltip>
    第<InputNumber size="small" class="w60" v-model="day"></InputNumber>天，
    <template v-if="isMoreFilter">
      第Q<InputNumber
        size="small"
        class="w60"
        v-model="filterQuestion"
      ></InputNumber
      >题，
    </template>
    <Button type="primary" size="small" @click="doAnaly">点击分析</Button>
    <Button type="primary" class="mar10l" size="small" @click="showFilterWorks"
      >筛选题目</Button
    >
    <Button
      type="primary"
      class="mar10l"
      size="small"
      @click="isShowAllWorks = true"
      >作业分析</Button
    >
    <br />
    <br />
    <span class="subtab">
      <a :class="{ cur: subTab === 1 }" @click="subTab = 1">基础日毕信息</a>---
      <template v-if="isShowExport">
        <a :class="{ cur: subTab === 2 }" @click="subTab = 2">导出题目</a>---
      </template>
      <a :class="{ cur: subTab === 3 }" @click="subTab = 3">设置</a>
      ---
      <Checkbox v-model="isBaseSortNormal">成员默认排序</Checkbox>
      --
      <Checkbox v-model="isShowLeavePeople">显示离开人员</Checkbox>
    </span>
    <br />
    <div class="mar10t" v-if="subTab === 3">
      记录开始标识：<input type="text" v-model="headerKey" />
      <br />
      记录结束标识：<input type="text" v-model="bottomKey" />
      <br />
      记录结束标识2：<input type="text" v-model="bottomKey2" />
      <br />
      标识开头：<input type="text" v-model="startKey" />
      <br />
      标识结束：<input type="text" v-model="endKey" />
    </div>
    <div class="questions-wrap mar10t" v-if="subTab === 2">
      <ExportQuestions
        :questions="questions"
        :answersObj="answersObj"
        :analyResult="analyResult"
        @showQuestion="showQuestion"
      ></ExportQuestions>
    </div>
    <br />
    <div v-if="subTab === 1">
      <table class="table table1">
        <tr>
          <th>序号</th>
          <th>QQ</th>
          <th>昵称</th>
          <th>
            提交时间
            <TableSort
              :order="getSortOrder('time')"
              @changeSort="changeSort('time', $event)"
            ></TableSort>
            <TablePoptip>
              <ul>
                <li>
                  <a @click="copyTime">复制时间到剪贴板</a>
                </li>
              </ul>
            </TablePoptip>
          </th>
          <th class="nowrap">
            总字数
            <TableSort
              :order="getSortOrder('count')"
              @changeSort="changeSort('count', $event)"
            ></TableSort>
          </th>
          <th>题号</th>
          <th class="text-left">
            <Checkbox v-model="isShowMoreOperate">操作</Checkbox>
          </th>
        </tr>
        <tr
          v-for="(item, index) in showList"
          :key="'analy_result_' + index"
          :class="{
            red: item.count === 0 || item.isDelay || item.headerError,
            orange: !item.isDelay && item.isLate,
          }"
        >
          <td class="center nowrap">{{ index + 1 }}</td>
          <td class="nowrap">{{ item.qq }}</td>
          <td class="nowrap">{{ item.nickname }}</td>
          <td class="nowrap">
            <template v-if="item.headerError"> 作业头错误 </template>
            <template v-else>
              {{ item.firstSubmitTime || item.time || "-"
              }}<template v-if="item.isDelay">（补）</template>
            </template>
          </td>
          <td>
            {{ item.count }}
          </td>
          <td>
            <Badge2
              v-for="(qa, qIndex) in item.qas"
              :key="'qa_' + index + '_' + qIndex"
              :name="qa.name"
              :text="qa.length"
              :color="qa.length <= 100 ? 'red' : 'green'"
            ></Badge2>
          </td>
          <td class="center">
            <a @click="showPeopleDayWork(index)">查看</a>
            <template v-if="isShowMoreOperate">
              <Tooltip transfer content="手动导入作业">
                <a class="mar10l" @click="startImportWork(item)">导入</a>
              </Tooltip>
              <Tooltip transfer content="复制到剪贴板,用于在补丁文件中">
                <a class="mar10l red" @click="copyWork(item)">复制</a>
              </Tooltip>
            </template>
          </td>
        </tr>
      </table>
    </div>
    <!-- 导入作业 -->
    <ModalImportWork
      title="导入作业"
      :importMember="importMember"
      v-if="isImportWork"
      @close="isImportWork = false"
      @save="doImportWork"
    ></ModalImportWork>
    <ModalPeopleWorks
      :list="workList"
      :people="showWorkPeople"
      v-if="isShowPeopleWork"
      @close="isShowPeopleWork = false"
    ></ModalPeopleWorks>
    <!-- 筛选作业 -->
    <ModalFilterWorks
      :filterObj="filterObj"
      v-if="isShowFilterWorks"
      @close="isShowFilterWorks = false"
    ></ModalFilterWorks>
    <!-- 作业分析 -->
    <ModalAllWorks
      v-if="isShowAllWorks"
      @close="isShowAllWorks = false"
    ></ModalAllWorks>
  </div>
</template>

<script>
import ModalPeopleWorks from "@/components/ModalPeopleWorks.vue";
import ModalFilterWorks from "@/components/ModalFilterWorks.vue";
import ModalAllWorks from "@/components/ModalAllWorks.vue";
import ModalImportWork from "@/components/ModalImportWork.vue";
import ExportQuestions from "@/components/ExportQuestions.vue";
import {
  cloneObj,
  splitPerson,
  parseTen,
  getDateByStr,
  getTimeByStr,
  exportCSV,
  splitQuetions,
  copy2Clipboard,
} from "js/utils.js";
let nickNameObj = null;
const dayjs = require("dayjs");
export default {
  data() {
    return {
      day: 1,
      isMoreFilter: false,
      filterQuestion: 93,
      headerKey: "#早起读书现学现卖#",
      bottomKey: "读书作业请不要在知识星球以及其他互联网渠道发表",
      bottomKey2: "行动攻略-S中国思想史专题读书",
      startKey: "持续行动第",
      endKey: "天",
      baseDate: "",
      analyResult: [],
      questions: [],
      answersObj: {},

      selectNums: 3, // 一共多少筛选人

      subTab: 1,
      isShowExport: false,
      sortKey: "count", // 排序key
      sortOrder: "desc", // 排序order
      isBaseSortNormal: false, // 成员默认排序
      isShowLeavePeople: false,
      isShowMoreOperate: false, // 显示更多操作
      // 导入作业
      isImportWork: false,
      importMemberIndex: -1,
      importMember: {},
      // 查看作业
      isShowPeopleWork: false,
      workList: [],
      showWorkPeople: null,

      filterObj: {
        isShowNO: true,
        isLockPeople: true,
        isLockQuestion: true,
      },
      isShowFilterWorks: false, // 筛选题目
      isShowAllWorks: false, // 所有作业
    };
  },
  computed: {
    showList() {
      let list = cloneObj(this.analyResult);
      if (!this.isShowLeavePeople) {
        list = list.filter((item) => !item.isLeave);
      }
      if (this.sortKey === "count") {
        list.sort((a, b) => {
          if (a.count === b.count) {
            return a.no > b.no ? 1 : -1;
          }
          if (this.sortOrder === "asc") {
            return a.count > b.count ? 1 : -1;
          }
          return a.count < b.count ? 1 : -1;
        });
      } else if (this.sortKey === "time") {
        list.sort((a, b) => {
          if (a.time && b.time) {
            if (this.sortOrder === "asc") {
              return dayjs(a.time).isAfter(b.time) ? 1 : -1;
            }
            return dayjs(a.time).isBefore(b.time) ? 1 : -1;
          }
          if (!a.time && !b.time) {
            return a.no > b.no ? 1 : -1;
          }
          if (!a.time) {
            return 1;
          }
          return -1;
        });
      } else if (this.sortKey === "no") {
        list.sort((a, b) => (a.no > b.no ? 1 : -1));
      }
      return list;
    },
    numbers() {
      return this.$store.getters.getMembers();
    },
  },
  watch: {
    isBaseSortNormal(newval) {
      if (newval) {
        this.sortKey = "no";
      } else {
        this.sortKey = "count";
        this.sortOrder = "desc";
      }
    },
  },
  methods: {
    initData() {
      let day = this.$store.getters.getStorageVal("day");
      this.day = day;
    },
    async doAnaly() {
      if (!this.day) {
        this.$global.log("请输入天数");
        return;
      }
      let text = await this.$global.getFileText("base");
      if (!text) {
        this.$global.log("请选择大群文件");
        return;
      }
      let members = this.numbers;
      if (members.length === 0) {
        this.$global.log("请先导入成员");
        return;
      }
      let isHaveResult = false;
      this.baseDate = "";
      let allList = splitPerson(text);
      let qqObj = {};
      nickNameObj = {};
      for (let i = 0, n = members.length; i < n; i++) {
        let item = members[i];
        qqObj[item.qq] = item;
        nickNameObj[item.nickname] = item;
      }
      let headerKey = this.headerKey;
      let searchKey = this.startKey + this.day + this.endKey;
      let bottomKey = this.bottomKey;
      let bottomKey2 = this.bottomKey2;
      let searchList = [];
      let noEndObj = {};
      for (let i = 0, n = allList.length; i < n; i++) {
        let item = allList[i];
        let content = allList[i].content;
        if (!content) {
          continue;
        }
        if (item.qq) {
          if (!qqObj[item.qq]) {
            continue;
          }
          if (item.nickname !== qqObj[item.qq].nickname) {
            item.nickname = qqObj[item.qq].nickname;
          }
        } else {
          if (!nickNameObj[item.nickname]) {
            continue;
          }
        }
        let isBottom =
          content.includes(bottomKey) || content.includes(bottomKey2);
        if (content.includes(headerKey) && noEndObj[item.nickname]) {
          let newItem = noEndObj[item.nickname];
          searchList.push(newItem);
          delete noEndObj[item.nickname];
        }
        if (content.includes(searchKey)) {
          if (
            this.isMoreFilter &&
            !content.includes("Q" + this.filterQuestion)
          ) {
            continue;
          }
          isHaveResult = true;
          if (!isBottom) {
            if (noEndObj[item.nickname]) {
              searchList.push(noEndObj[item.nickname]);
            }
            noEndObj[item.nickname] = item;
            continue;
          }
          if (!content.includes(headerKey)) {
            item.headerError = true;
          }
          searchList.push(item);
        } else {
          if (isBottom && noEndObj[item.nickname]) {
            let newItem = noEndObj[item.nickname];
            newItem.content += content;
            searchList.push(newItem);
            delete noEndObj[item.nickname];
          }
        }
      }
      for (let key in noEndObj) {
        searchList.push(noEndObj[key]);
      }
      let analyResult = [];

      for (let i = 0, n = searchList.length; i < n; i++) {
        let item = searchList[i];
        let resultItem = this.getResultItem(item);
        analyResult.push(resultItem);
      }
      analyResult = analyResult.sort((a, b) => (a.time > b.time ? 1 : -1));
      let obj = {};
      for (let i = analyResult.length - 1; i >= 0; i--) {
        let item = analyResult[i];
        if (obj[item.qq]) {
          analyResult.splice(i, 1);
          obj[item.qq].firstSubmitTime = item.time;
          obj[item.qq].isDelay = item.isDelay;
          obj[item.qq].isLate = item.isLate;
        } else {
          obj[item.qq] = item;
        }
      }

      let resultNicknames = analyResult.map((item) => item.nickname);
      let noResult = members.filter(
        (item) => !resultNicknames.includes(item.nickname)
      );
      for (let i = 0, n = noResult.length; i < n; i++) {
        let item = noResult[i];
        analyResult.push({
          qq: item.qq,
          nickname: item.nickname,
          count: 0,
          isLeave: item.isLeave,
          no: item.no,
        });
      }
      this.analyResult = analyResult;
      this.analyQuestions();
      new this.$tableSelect(".base-box-wrap .table");
      if (isHaveResult) {
        this.$store.commit("saveStorage", {
          tag: "day",
          num: this.day,
        });
      }
    },
    getResultItem(item) {
      let lateTime = "23:30:00";
      let isDelay = false;
      let isLate = false;
      if (item.time) {
        let addDate = getDateByStr(item.time);
        let time = getTimeByStr(item.time);
        if (!this.baseDate) {
          this.baseDate = addDate;
        }
        if (addDate > this.baseDate) {
          isDelay = true;
        }
        if (time > lateTime) {
          isLate = true;
        }
      }
      return {
        qq: item.qq || nickNameObj[item.nickname].qq,
        nickname: item.nickname,
        time: item.time,
        count: item.content.length,
        title: item.title,
        content: item.content,
        isDelay: isDelay,
        isLate: isLate,
        isLeave: nickNameObj[item.nickname].isLeave,
        headerError: item.headerError,
        no: nickNameObj[item.nickname].no,
      };
    },
    // 分析题目
    analyQuestions() {
      this.answersObj = {};
      let qNumObj = {};
      for (let i = 0, n = this.analyResult.length; i < n; i++) {
        let content = this.analyResult[i].content;
        if (!content) {
          continue;
        }
        let qas = splitQuetions(content);
        for (let j = 0, m = qas.length; j < m; j++) {
          let name = qas[j].name;
          if (!qNumObj[name]) {
            qNumObj[name] = 1;
          } else {
            qNumObj[name] += 1;
          }
        }
      }
      let allLen = this.analyResult.length;
      for (let name in qNumObj) {
        if (qNumObj[name] < allLen / 2) {
          delete qNumObj[name];
        }
      }

      let filterQuestions;
      if (this.analyResult.length > 0) {
        filterQuestions = splitQuetions(this.analyResult[0].content);
        filterQuestions = filterQuestions.filter((item) => qNumObj[item.name]);
      }
      let obj = {};
      for (let i = 0, n = this.analyResult.length; i < n; i++) {
        let content = this.analyResult[i].content;
        let qq = this.analyResult[i].qq;
        if (!content) {
          continue;
        }
        let qas = splitQuetions(content, filterQuestions);
        this.analyResult[i].qas = qas;
        for (let j = 0, m = qas.length; j < m; j++) {
          let question = qas[j].question;
          let name = qas[j].name;
          let answer = qas[j].answer;
          if (!this.answersObj[name]) {
            this.answersObj[name] = [];
          }
          this.answersObj[name].push({
            qq: qq,
            question: question,
            answer: answer,
          });
          if (obj[name] === undefined) {
            obj[name] = question;
          }
        }
      }

      let questions = [];
      for (let name in obj) {
        let question = obj[name];
        questions.push({
          name: name,
          question: question,
        });
      }
      this.questions = questions;
      this.isShowExport = true;
    },
    // 更改排序
    changeSort(key, order) {
      this.sortKey = key;
      this.sortOrder = order;
    },
    // 获取排序order
    getSortOrder(key) {
      if (key === this.sortKey) {
        return this.sortOrder;
      }
      return "";
    },

    exportNO() {
      let header = ["昵称", "QQ", "编号"];
      let list = this.analyResult.map((item) => [
        item.nickname,
        item.qq,
        item.no,
      ]);
      exportCSV(header, list, "编号.csv");
    },
    // 导入作业
    doImportWork(obj) {
      let time = obj.time;
      let content = obj.content;

      let item = this.importMember;
      let index = this.importMemberIndex;
      let title = `${time} ${item.nickname}(${item.qq})`;

      item.time = time;
      item.count = content.length;
      item.title = title;
      item.content = content;
      let resultItem = this.getResultItem(item);
      this.analyResult[index] = resultItem;
      this.$set(this.analyResult, index, this.analyResult[index]);
      this.analyQuestions();
      this.isImportWork = false;
    },
    startImportWork(item) {
      let index = -1;
      for (let i = 0, n = this.analyResult.length; i < n; i++) {
        let item2 = this.analyResult[i];
        if (item.qq === item2.qq) {
          index = i;
          break;
        }
      }
      // 准备导出
      this.importMemberIndex = index;
      this.importMember = this.analyResult[index];

      this.isImportWork = true;
    },
    //
    showFilterWorks() {
      this.filterObj = {
        isShowNO: false,
        isLockPeople: false,
        isLockQuestion: false,
      };
      this.isShowFilterWorks = true;
    },
    // 展示问题
    showQuestion(index, isAnonymousQuestions) {
      let name = this.questions[index].name;
      this.filterObj = {
        isShowNO: isAnonymousQuestions,
        isLockPeople: isAnonymousQuestions,
        isLockQuestion: isAnonymousQuestions,
        question: name,
      };
      this.isShowFilterWorks = true;
    },
    // 查看单人当天作业
    showPeopleDayWork(index) {
      let item = this.showList[index];
      let workList = [];
      workList.push(item);
      this.workList = workList;
      this.showWorkPeople = nickNameObj[item.nickname];
      this.isShowPeopleWork = true;
    },
    // 复制时间
    copyTime() {
      let str = "";
      for (let i = 0, n = this.showList.length; i < n; i++) {
        let item = this.showList[i];
        let time = item.firstSubmitTime || item.time;
        if (!time) {
          str += "-";
        } else if (item.headerError) {
          str += "-";
        } else if (item.isDelay) {
          str += `${time}（补）`;
        } else {
          str += getTimeByStr(time);
        }
        str += "\n";
      }
      copy2Clipboard(str);
      this.$Message.info("复制成功!");
    },
    // 复制作业
    copyWork(item) {
      if (!item.time) {
        this.$Message.info("无作业可复制");
        return;
      }
      let str = "";
      str += `${item.title}\n${item.content}\n`;
      copy2Clipboard(str);
      this.$Message.info("复制成功!");
    },
    formatTime(str, isDelay) {
      if (isDelay) {
        return str;
      }
      return getTimeByStr(str);
    },
  },
  mounted() {
    this.initData();
  },
  components: {
    ModalPeopleWorks,
    ModalFilterWorks,
    ModalAllWorks,
    ModalImportWork,
    ExportQuestions,
  },
};
</script>

<style lang="less"></style>
